
from decimal import Decimal
from django.http import JsonResponse
from django.views import View
from django_redis import get_redis_connection

from goods.models import SKU
from huamei_mall.utils.view import LoginRequiredMixin
from users.models import Address

"""结算订单"""
class OrderSettlementView(LoginRequiredMixin, View):
    def get(self,request):
        #  1获取地址信息addresses；
        #  2获取skus
        user = request.user

        try:
            addresses = Address.objects.filter(user=request.user,
                                               is_deleted=False)
        except Exception as e:

            return None

        '''从Redis购物车中查询出被勾选的商品信息'''
        redis_conn = get_redis_connection('carts')
        # 从hash表里拿 sku_id ,count     hgetall(key)==hkeys(key)   返回  sku_id: {field1:value1},{field2:value2}
        item_dict = redis_conn.hgetall('carts_%s'% user.id)
        # set 表里拿 sku_id  , selected   （smembers key）返回key的所有元素  sku_id: value1,value2...
        cart_selected = redis_conn.smembers('selected_%s' % user.id)

        cart = {}
        item_dict = redis_conn.hgetall('carts_%s'% user.id)
        #
        cart_selected = redis_conn.smembers('selected_%s'% user.id)
        for sku_id in cart_selected:
            #  把 cart_selected 的key，value整数化。组成一个新字典

            #  把bytes类型，转成整形 。  下面skus id__in  要的是整形keys
            # {sku.id:count}
            cart[int(sku_id)] = int(item_dict[sku_id])

        # 查询商品信息
        sku_list = []
        skus = SKU.objects.filter(id__in=cart.keys())

        for sku in skus:
            sku_list.append({
                "id": sku.id,
                "name": sku.name,
                "default_image_url": sku.default_image_url,
                # cart[sku.id] = sku_id  是数字。
                "count":cart[sku.id],
                "price": sku.price,
            })


        list  = []
        for address in addresses:
            list.append({"id": address.id,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "receiver":address.receiver,
             })

        freight = Decimal('10.00')

        return JsonResponse({'code':0,
                                  'state':'OK',
                                  'context':{
                                      'addresses':list,
                                      'skus':sku_list,
                                      'freight':freight
                                  }
                                  })